<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <!-- 搜索添加框 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input
            placeholder="请输入商品名字"
            v-model="searchGoods"
            clearable
            @clear="clearSearch"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="handleSearch"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="7">
          <el-button type="primary" @click="addGoods">添加商品</el-button>
        </el-col>
      </el-row>

      <!-- 内容表格区 -->
      <el-table :data="goodsList" style="width: 100%" border stripe lazy>
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="goods_name" label="商品名称"> </el-table-column>
        <el-table-column prop="goods_price" label="商品价格(元)" width="110">
        </el-table-column>
        <el-table-column prop="goods_weight" label="商品重量" width="100">
        </el-table-column>
        <el-table-column prop="add_time" label="创建时间" width="160">
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template slot-scope="scope">
            <el-button type="primary" size="mini">编辑</el-button>
            <el-button type="danger" size="mini" @click="removeGood(scope.row.goods_id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <el-pagination
        @current-change="changeCurrent"
        @size-change="changeSize"
        :current-page="pagenum"
        :page-sizes="[5, 10, 20, 30]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="goods.total"
        background
      >
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 搜索商品数据
      searchGoods: "",
      // 商品列表数据
      goods: {},
      //页码
      pagenum: 1,
      // 一页展示数据
      pagesize: 10,
    };
  },
  computed: {
    goodsList() {
      return this.goods.goods || [];
    },
  },
  methods: {
    // 获取商品列表数据
    async getGoodsList() {
      const { data: res } = await this.$http.get("goods", {
        params: {
          query: this.searchGoods,
          pagenum: this.pagenum,
          pagesize: this.pagesize,
        },
      });
      if (res.meta.status !== 200) {
        return this.$message.error("获取商品列表失败");
      }
      res.data.goods.forEach((item) => {
        let time = new Date(item.add_time);
        let y = time.getFullYear();
        let m = (time.getMonth() + 1 + '').padStart(2,'0'); //getMonth从0开始(0~11),所以要加1
        let d = (time.getDate()+'').padStart(2,'0');
        let h = (time.getHours()+'').padStart(2,'0');
        let mm = (time.getMinutes()+'').padStart(2,'0');
        let s = (time.getSeconds()+'').padStart(2,'0');
        let newTime = `${y}-${m}-${d} ${h}:${mm}:${s}`;
        item.add_time = newTime;
      });
      this.goods = res.data;
      console.log(this.goods);
    },
    // 当currentPage当前页改变时触发这个函数
    changeCurrent(newCurrent) {
      console.log(newCurrent);
      this.pagenum = newCurrent;
      this.getGoodsList();
    },
    // 当改变显示总条数的时候触发这个函数
    changeSize(newSize) {
      console.log(newSize);
      this.pagesize = newSize;
      this.getGoodsList();
    },
    // 点击搜索按钮搜索商品
    handleSearch() {
      this.getGoodsList();
    },
    // 点击按钮添加商品
    addGoods() {
      // 跳转路由
      this.$router.push("/goods/add");
    },
    // 删除输入框内容后触发这个函数
    clearSearch() {
      this.getGoodsList();
    },
    // 点击删除按钮删除商品
    removeGood(id){
       this.$confirm('此操作将永久删除该商品, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const {data:res} = await this.$http.delete(`goods/${id}`)
          if(res.meta.status !== 200){
            throw new Error
          }
          this.getGoodsList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '删除失败'
          });          
        });
    }
  },
  mounted() {
    this.getGoodsList();
  },
};
</script>

<style scoped lang="less">
.el-table {
  margin-top: 10px;
}
</style>